package io.github.handyang.algorithms;

import com.google.common.collect.Lists;

import java.util.Iterator;

public class Bag<V> implements Iterable<V> {
    private Node head;

    private Node tail;

    public void add(V v) {
        Node node = new Node(v);

        if (tail != null) {
            tail.next = node;
            tail = tail.next;
            return;
        }

        head = node;
        tail = node;
    }

    public boolean isEmpty() {
        return head == null;
    }

    @Override
    public Iterator<V> iterator() {
        return new Itr();
    }

    @Override
    public String toString() {
        return Lists.newArrayList(this).toString();
    }

    private final class Itr implements Iterator<V> {
        private Node cursor = Bag.this.head;

        @Override
        public boolean hasNext() {
            return cursor != null;
        }

        @Override
        public V next() {
            Node next = cursor.next;
            V value = cursor.value;
            cursor = next;
            return value;
        }
    }

    private final class Node {
        private V value;

        private Node next;

        public Node(V value) {
            this.value = value;
        }
    }
}
